<template>
  <el-dialog
      title="党建工作方案更新"
      :visible.sync="visible" :center="true"
      width="70%" :close-on-click-modal="false">
    <el-descriptions :column="3" border size="mini" label-class-name="my-label">
      <el-descriptions-item label="任务名称">{{ title }}</el-descriptions-item>
      <el-descriptions-item label="任务负责人">{{ personInCharge }}
      </el-descriptions-item>
      <el-descriptions-item label="完成时间">{{ endTime }}</el-descriptions-item>
    </el-descriptions>
    <el-table :data="indicatorDetailScheme" size="mini" border header-cell-class-name="my-label">
      <el-table-column header-align="center" min-width="5%" type="index" label="序号"
                       align="center"></el-table-column>
      <el-table-column header-align="center" label="方案内容" min-width="42.5%">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.schemeContent" :disabled="!isSchemeEditing"></el-input>
        </template>
      </el-table-column>
      <el-table-column header-align="center" min-width="42.5%" label="附件"
                       style="display: flex; justify-content: space-between">
        <template slot-scope="scope">
          <el-upload v-if="!scope.row.kpiSchemeAttachments || scope.row.kpiSchemeAttachments.length === 0"
                     :action="uploadAction" :with-credentials="true"
                     multiple :disabled="!isSchemeEditing"
                     :on-success="(response, file, fileList) => handleSchemeSuccess(scope.row,response, file, fileList)"
                     :file-list="schemeFileLists[scope.row.index]" :show-file-list="false">
            <el-button size="mini" type="text" icon="el-icon-paperclip"></el-button>
          </el-upload>
          <!-- 附件链接和删除按钮 -->
          <div v-for="(att, idx) in scope.row.kpiSchemeAttachments" :key="idx"
               style="display: inline-flex; align-items: center; margin-right: 0.5rem;">
            <el-link
                v-if="att.filePath"
                :href="att.filePath"
                target="_blank"
                type="primary"
                size="mini"
            >
              {{ att.filePath.split('/').pop() }}
            </el-link>

            <!-- 删除按钮 -->
            <el-button
                v-if="isSchemeEditing"
                size="mini"
                type="text"
                icon="el-icon-close"
                @click.stop="handleDeleteSchemeAttachment(att, scope.row)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column header-align="center" min-width="10%" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="deleteSchemeRow(scope.$index)"
                     icon="el-icon-delete" :disabled="!isSchemeEditing"></el-button>
          <el-button type="text" size="mini" @click="addSchemeRow(scope.$index)"
                     icon="el-icon-plus" :disabled="!isSchemeEditing" v-if="scope.$index == indicatorDetailScheme.length - 1"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="update" size="mini" :disabled="!isSchemeEditing">更新</el-button>
      <el-button type="primary" size="mini" @click="editScheme">编辑</el-button>
      <el-button type="primary" size="mini" @click="cancle">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "SchemeUpdate",
  data() {
    return {
      visible: false,
      indicatorDetailScheme:[],
      title:'',
      personInCharge:'',
      endTime:'',
      uploadAction: `${process.env.VUE_APP_API_BASE_URL}/file/upload`,
      schemeFileLists: [[]],
      isSchemeEditing: false,
      indicatorDetailId:0,
    }
  },
  methods: {
    addSchemeRow() {
      this.indicatorDetailScheme.push({
        id: null,
        indicatorDetailId: '',
        schemeContent: '',
        status: '未审批',
        kpiSchemeAttachments: []
      })
      this.schemeFileLists.push([])
    },
    deleteSchemeRow(index) {
      const row = this.indicatorDetailScheme[index];
      if (!row || !row.id) {
        this.indicatorDetailScheme.splice(index, 1);
        return;
      }
      this.$confirm('确定删除该行方案吗？', '提示', {type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消'}).then(() => {
        this.$http.delete(`/kpi/detail/scheme/${row.id}`).then(response => {
          if (response.data.code === 1) {
            this.$message.success('删除成功');
            this.indicatorDetailScheme.splice(index, 1);
          } else {
            this.$message.error('删除失败');
          }
        })
      })
    },
    handleTaskSuccess(row, response, file, fileList) {
      const attachment = {
        filePath: response.data,
        source: '发布时',
        taskId: ''
      }
      row.releaseAttachments.push(attachment)
    },
    handleDeleteSchemeAttachment(att, row) {
      const idx = row.kpiSchemeAttachments.indexOf(att);
      if (idx > -1) {
        row.kpiSchemeAttachments.splice(idx, 1);
        if (att.id) {
          this.attachmentsToDelete.push(att.id);
        }
      }
    },
    handleSchemeSuccess(row, response, file, fileList) {
      const idx = this.indicatorDetailScheme.indexOf(row)
      if (idx != -1) {
        this.schemeFileLists[idx] = fileList
      }
      const attachment = {
        filePath: response.data
      }
      row.kpiSchemeAttachments.push(attachment)
    },
    editScheme() {
      this.isSchemeEditing = true
    },
    update() {
      const indicatorDetailScheme = this.indicatorDetailScheme.map(item => ({
        ...item,
        indicatorDetailId: this.indicatorDetailId
      }));
      const submitSchemeDTO = {
        indicatorDetailSchemes: indicatorDetailScheme,
        attachmentsToDelete: this.attachmentsToDelete
      }
      console.log(JSON.stringify(submitSchemeDTO, null, 2))
      this.$http.post("/kpi/detail/scheme/update_process_scheme", submitSchemeDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message.success("方案更新成功，请等待复审");
          this.attachmentsToDelete = [];
          this.isSchemeEditing = false
        } else {
          this.$message.error("提交失败");
        }
      });
      this.visible = false
    },
    cancle() {
      this.visible = false
    }
  },
  mounted() {
    this.visible = true
    const taskId = this.$store.state.taskId
    this.$http.get(`/kpi/scheme/${taskId}`).then((kpiRes) => {
      if (kpiRes.data.code == 1) {
        this.indicatorDetailScheme = kpiRes.data.data
        console.log(JSON.stringify(this.indicatorDetailScheme, null, 2))
        this.title = this.indicatorDetailScheme[0].title
        this.endTime = this.indicatorDetailScheme[0].endTime
        this.personInCharge = this.indicatorDetailScheme[0].personInCharge
        this.indicatorDetailId = this.indicatorDetailScheme[0].indicatorDetailId
      }
    })
  }
}
</script>